package com.cheetah.start.common.plugin.log;


import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * 控制台记录所有接口请求
 *
 * @author xjhmwj
 * @date 2021/1/25 14:12
 */
@Aspect
@Component
@Slf4j
public class ConsoleLogAspect {

    @Pointcut("execution(public * com.cheetah.start..*.controller..*.*(..))")
    public void webLog() {
    }

    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) {
        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        String classmethod = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName();
        String replace = classmethod.replace("com.cheetah.start.module.test.controller.", "");
        UserAgent parse = UserAgentUtil.parse(request.getHeader("User-Agent"));
        // 记录下请求内容
        log.info("--START-- , 接口地址:[{}], 请求方式 :[{}] ,IP地址 :[{}], 类方法 :[{}], 参数 :[{}], 其他信息 :[{}]",
                request.getRequestURL(),
                request.getMethod(),
                request.getRemoteAddr(),
                replace,
                Arrays.toString(joinPoint.getArgs()),
                parse.getBrowser().getName() + " | " + parse.getVersion() + " | " + parse.getOs()
        );
    }


    @AfterReturning(returning = "ret", pointcut = "webLog()")
    public void doAfterReturning(Object ret) {
        // 处理完请求，返回内容
        if (ret != null){
            String s = ret.toString();
            if (s != null && s.length() > 500) {
                String substring = s.substring(0, 500);
                log.info("--END-- 请求结果 :[{}]", substring);
            } else {
                log.info("--END-- 请求结果 :[{}]", s);
            }
        }
        log.info("--END-- 请求结果 :[{}]", ret);
    }

    @Around("webLog()")
    public Object timing(ProceedingJoinPoint joinPoint) throws Throwable {
        Object object;
        long start = System.currentTimeMillis();
        object = joinPoint.proceed();
        long l = System.currentTimeMillis() - start;
        log.info("请求耗时:[{}]MS", l);
        if (l > 2000) {
            log.warn("注意:请求耗时过长,耗时:[{}]MS", l);
        }
        return object;
    }

}
